package com.omenkk.juc.c2;

import lombok.extern.slf4j.Slf4j;

@Slf4j

//由于counter++操作在字节码层面不是原子的
//多个线程对共享资源读写操作时发生指令交错，出现并发问题
//一段代码块内如果存在对共享资源的多线程读写操作，称这段代码块为临界区
public class demo1 {
    static int counter=0;
static final Object lock=new Object();
 public static void main(String[] args) throws InterruptedException {
//test1();
  //   test2();
     room r1=new room();
     Thread t1=new Thread(()->{
         for(int i=0;i<5000;i++){
           r1.increment();
         }
     },"t1");
     Thread t2=new Thread(()->{
         for(int i=0;i<5000;i++){
             r1.decrement();
         }
     },"t2");
     t1.start();
     t2.start();
     t1.join();
     t2.join();
     log.debug("counter:{}",r1.get());
 }
    private static void test1() throws InterruptedException {
                Thread t1=new Thread(()->{
            for(int i=0;i<5000;i++){
                counter++;
            }
        },"t1");
        Thread t2=new Thread(()->{
            for(int i=0;i<5000;i++){
                counter--;
            }
        },"t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    log.debug("counter:{}",counter);
    }
    private static void test2() throws InterruptedException {
        Thread t1=new Thread(()->{
            for(int i=0;i<5000;i++){
                synchronized (lock){
                    counter++;
                }
            }
        },"t1");
        Thread t2=new Thread(()->{
            for(int i=0;i<5000;i++){
                synchronized (lock){
                    counter--;
                }
            }
        },"t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("counter:{}",counter);
    }

}

class room{
    int value=0;
    public void increment(){
        synchronized (this){
            value++;
        }
    }
    public void decrement(){
        synchronized (this){
            value--;
        }
    }
    public int get(){
        synchronized (this){
            return value;
        }
    }
}